package com.rest.demo.mybatisdemo.controller;

import com.rest.demo.mybatisdemo.entity.Account;
import com.rest.demo.mybatisdemo.service.IAccountService;
import com.rest.demo.response.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author Administrator
 * @decription
 * @Date 2017-11-14 16:02
 */
@RestController
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @GetMapping(value = "/account")
    public ResponseEntity findAll() {
        return new ResponseEntity().success(accountService.findAccountList());
    }

    @GetMapping(value = "/account/{id}")
    public ResponseEntity findById(@PathVariable("id") Integer id) {
        return new ResponseEntity().success(accountService.findAccount(id));
    }

    @PostMapping(value = "/account")
    public ResponseEntity saveAccount(@RequestBody @Valid Account account) {
        int result = accountService.add(account.getName(),account.getMoney());
        if(result == 1) {
            return new ResponseEntity().success();
        } else {
            return new ResponseEntity().failure();
        }
    }

    @PutMapping(value = "/account/{id}")
    public ResponseEntity updateAccount(@PathVariable("id") Integer id,@RequestBody @Valid Account account) {
        int result = accountService.update(account.getName(),account.getMoney(),id);
        if(result == 1) {
            return new ResponseEntity().success();
        } else {
            return new ResponseEntity().failure();
        }
    }

    @DeleteMapping(value = "/account/{id}")
    public ResponseEntity deleteAccount(@PathVariable("id") Integer id) {
        int result = accountService.delete(id);
        if(result == 1) {
            return new ResponseEntity().success();
        } else {
            return new ResponseEntity().failure();
        }
    }
}
